<template>
  <!-- 自定义日期 -->
  <customRangeVue @update-between-time="handleBetweenTime" @between-choose-index="handleBetweenTimeChoose">
    <!-- 具名插槽---区域类型 -->
    <template v-slot:custom>
      <view class="show-type-list" style="box-sizing: border-box">
        <view class="flex-row text-space">
          <picker @change="bindPickerChange" :value="chooseIndex" :range="areaTypeArray">
            <view class="text-name">{{ areaTypeArray[chooseIndex] }}</view>
          </picker>
          <view style="margin-left: 8rpx;">
            <uni-icons type="down" size="14" :color="iconColor"></uni-icons>
          </view>
        </view>
        <view style="width: 100%;">
          <scroll-view scroll-x="true" :show-scrollbar="false" style="width: calc(100% - 114rpx)">
            <view style="display: flex; flex-direction: row;" v-if="typeAreaIndex == 0">
              <checkbox-group @change="checkboxValue" style="display: flex;flex-direction: row;">
                <view class="choose-type-area" v-for="(item, index) in areaTypeList.area" :key="index">
                  <checkbox :checked="item.checked" :value="item.area_id" style="scale: 0.7;"/>
                  <view>
                    {{ item.area_name }}
                  </view>
                </view>
              </checkbox-group>
            </view>
            <view style="display: flex; flex-direction: row;flex: 1;white-space: nowrap;box-sizing: border-box;" v-else>
              <checkbox-group @change="checkboxValue" style="display: flex;flex-direction: row;">
                <view class="choose-type-area" v-for="(item, index) in areaTypeList.type" :key="index">
                  <checkbox :checked="item.checked" backgroundColor="grey" borderColor="#000000"
                            activeBorderColor="#000000" :value="item.type_id" style="scale: 0.7;"/>
                  <view>
                    {{ item.type_name }}
                  </view>
                </view>
              </checkbox-group>
            </view>
          </scroll-view>
        </view>
      </view>
      <view style="height: 88rpx;padding: 0 30rpx;line-height: 88rpx">
        <picker @change="bindPickerChangeShop" :value="shopIndex"
                :range="shopList.map(item=>item.shop_alias)">
          <view class="flex-row flex-jus-bet" style="width: 100%;flex: 1">
            <view class="flex-row">
              <view class="f-s-28" style="color: var(--grey-text);">当前门店：</view>
              <view class="f-s-28" style="color: var(--white-text);align-items: center;">
                {{ shopList[shopIndex].shop_alias }}
              </view>
            </view>
            <view class="flex-row">
              <view class="f-s-28" style="color: #0A84FF;align-items: center">
                切换门店
              </view>
              <view style="margin-left: 4rpx">
                <uni-icons type="down" size="14" color="#0A84FF"></uni-icons>
              </view>
            </view>

          </view>
        </picker>
      </view>
      <view class="line-split"></view>
    </template>
  </customRangeVue>

  <scroll-view class="scroll" scroll-y refresher-enabled="true" :refresher-background="bgColorRefresh"
               :refresher-triggered="triggered" :refresher-threshold="80" @scrolltolower="finishPullUp"
               @refresherrefresh="refresher" :show-scrollbar="false">
    <view class="body-child">
      <!-- 汇总统计 -->
      <trade-total :totalBusinessList="totalBusinessList" :betweenTime="betweenTime"
                   @business-open="businessOpenDetail"></trade-total>
      <!-- 营业日统计 -->
      <trade-day :dayBusinessList="dayBusinessList" :totalBusinessList="totalBusinessList" :betweenTime="betweenTime"
                 @business-open="businessOpenDetail"></trade-day>

      <view class="load-bottom">
        <view v-if="loadingFlag == 1" class="load_in" :class="loadingFlag == 1 ? 'load_in_ani' : ''">
          <uni-icons type="spinner-cycle" size="30" color="#ff6f3f"></uni-icons>
        </view>
        <view v-show="loadingFlag == 2" class="load_over">数据已全部加载~</view>
      </view>
    </view>
  </scroll-view>
  <trade-business-popup ref="business"></trade-business-popup>
  <trade-total-popup ref="total"></trade-total-popup>
  <trade-receipts-popup ref="receipts"></trade-receipts-popup>
  <trade-member-popup ref="member"></trade-member-popup>
  <custom-loading-vue ref="loading"></custom-loading-vue>
</template>
<script setup>
import customRangeVue from '@/components/customRange.vue'
import tradeBusinessPopup from '/pages/application/business_sta_child/trade_bounce_business.vue'
import tradeTotalPopup from '/pages/application/business_sta_child/trade_bounce_total.vue'
import tradeReceiptsPopup from '/pages/application/business_sta_child/trade_bounce_receipts.vue'
import tradeMemberPopup from '/pages/application/business_sta_child/trade_bounce_member.vue'
import tradeDay from '/pages/application/business_sta_child/trade_child_day.vue'
import tradeTotal from '/pages/application/business_sta_child/trade_child_total.vue'
import customLoadingVue from '@/components/customLoading.vue'
import {
  watch,
  ref,
  nextTick,
  getCurrentInstance
} from 'vue'
import {
  onLoad
} from '@dcloudio/uni-app'

const instance = getCurrentInstance()
const commonJs = instance?.proxy?.$commonJs
const shopIndex = ref(commonJs.getChooseShopIndex())
const shopList = ref(commonJs.getShopList())
const loading = ref(Object)
const bgColorRefresh = ref('var(--bg-color)')
const betweenTimeIndex = ref(0)
const betweenTime = ref([])
const iconColor = ref('var(--white-text)')
const triggered = ref(false)
const canvasHeight = ref(0)
const canvasWidth = ref(0)
const canvas = ref(Object)
const business = ref(Object)
const total = ref(Object)
const receipts = ref(Object)
const member = ref(Object)
const areaTypeList = ref({
  type: [],
  area: [],
})
const typeAreaIndex = ref(0) // 0代表区域 1代表类型
const areaTypeArray = ref(['按区域', '按类型'])
const areaChooseArray = ref([])
const typeChooseArray = ref([])
const chooseIndex = ref(0)
const pagesData = ref({
  page: 1,
  limit: 5,
  total: 0
})
const dayBusinessList = ref([])
const totalBusinessList = ref({})
const loadingFlag = ref(0)

onLoad(() => {
  getAreaList()
  getTypeList()
})

/**
 * 门店切换
 * @param e
 */
const bindPickerChangeShop = (e) => {
  if (e.detail.value >= 0 && e.detail.value != commonJs.systemConfig.shopIndex) {
    shopIndex.value = e.detail.value
    commonJs.systemConfig.shopIndex = e.detail.value
    commonJs.setStorage(
        'shopIndex',
        e.detail.value,
        function () {
          commonJs.logger.debug('设置门店成功！')
        }
    )
    // 切换门店后进行请求操作
    resetPages()
    let day = getDaysDifference(betweenTime.value[0], betweenTime.value[1])
    if (day > 1) {
      getTotalBusiness()
    }
    getDayBusiness()
  }
}

/**
 * 打开弹出层
 * @param e
 */
const businessOpenDetail = (e) => {
  if (e.type) {
    switch (e.type) {
      case 'total':
        total.value.opens(e.item)
        break
      case 'business':
        business.value.opens(e.item, e.date)
        break
      case 'receipts':
        receipts.value.opens(e.item)
        break
      case 'member':
        member.value.opens(e.item, e.date)
        break
      default:
        uni.showToast({
          title: '未找到标识',
          icon: 'none',
          duration: 1500
        })
    }
  }

}

/**
 * 切换picker选择
 * @param e 选择的索引
 */
const bindPickerChange = async (e) => {
  areaChooseArray.value = []
  typeChooseArray.value = []
  if (e.detail.value == 0) {
    areaTypeList.value.type.map(item => {
      item.checked = false
      return item
    })
  } else {
    areaTypeList.value.area.map(item => {
      item.checked = false
      return item
    })
  }
  if (e.detail.value != chooseIndex.value) {
    chooseIndex.value = e.detail.value
    typeAreaIndex.value = e.detail.value
    resetPages()
    let day = getDaysDifference(betweenTime.value[0], betweenTime.value[1])
    if (day > 1) {
      getTotalBusiness()
    }
    getDayBusiness()
  }
}

/**
 * 选择区域或类型
 * @param e
 * @return {Promise<void>}
 */
const checkboxValue = (e) => {
  if (typeAreaIndex.value == '0') {
    areaChooseArray.value = e.detail.value
  } else {
    typeChooseArray.value = e.detail.value
  }
  resetPages()
  let day = getDaysDifference(betweenTime.value[0], betweenTime.value[1])
  if (day > 1) {
    getTotalBusiness()
  }
  getDayBusiness()
}

/**
 * 日期选择索引
 * @param index
 */
const handleBetweenTimeChoose = (index) => {
  betweenTimeIndex.value = index
}

/**
 * 日期选择
 * @param timeRange
 */
const handleBetweenTime = (timeRange) => {
  betweenTime.value = timeRange
}

/**
 * 监听日期
 */
watch(betweenTime, (newValue, oldValue) => {
  if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
    // 清空日数据重新渲染
    resetPages()
    let day = getDaysDifference(betweenTime.value[0], betweenTime.value[1])
    if (day > 1) {
      getTotalBusiness()
    }
    getDayBusiness()
  }
}, {
  deep: true
})

/**
 * 水印
 */
const watermarkApi = () => {
  const querys = uni.createSelectorQuery().in(this);
  querys.select('.body-child').boundingClientRect(data => {
    if (data) {
      canvasHeight.value = data.height;
      canvasWidth.value = data.width;
      nextTick(() => {
        setTimeout(() => {
          canvas.value.drawWatermark()
        }, 300)
      })
    }
  }).exec();
}

/**
 * 下拉刷新操作
 * @param e
 * @return {Promise<void>}
 */
const finishPullUp = async (e) => {
  if (loadingFlag.value == 1 || loadingFlag.value == 2) {
    return
  }
  let pages = Math.ceil(pagesData.value.total / pagesData.value.limit)
  if (pagesData.value.page >= pages) {
    loadingFlag.value = 2
    return
  }
  if (loadingFlag.value == 0) {
    loadingFlag.value = 1
    pagesData.value.page++
    getDayBusiness()
    setTimeout(() => {
      loadingFlag.value = 0
    }, 200)
  }
}

const refresher = (e) => {
  if (!triggered.value) {
    triggered.value = true
    resetPages()
    let day = getDaysDifference(betweenTime.value[0], betweenTime.value[1])
    if (day > 1) {
      getTotalBusiness()
    }
    getDayBusiness()
    setTimeout(() => {
      triggered.value = false
    }, 200)
  }
}

/**
 * 初始化
 */
const resetPages = () => {
  pagesData.value.page = 1
  loadingFlag.value = 0
  dayBusinessList.value = []
  totalBusinessList.value = {}
}

/**
 * 获取汇总营业额
 */
const getTotalBusiness = () => {
  const params = {
    begin_date: betweenTime.value[0] + ' 12:00:00',
    end_date: betweenTime.value[1] + ' 12:00:00'
  }
  if (typeAreaIndex.value == 0) {
    params.area_id = areaChooseArray.value.join()
  }
  if (typeAreaIndex.value == 1) {
    params.type_id = typeChooseArray.value.join()
  }
  commonJs.queryCache('/app/admin/getMoneyTotal', params, {
    before() {
    },
    success(res) {
      try {
        const {
          code,
          data,
          msg,
          server_ip
        } = res
        totalBusinessList.value = data
      } catch (error) {
        commonJs.showMessage(error)
      }
    },
    fail(err) {
      commonJs.logger.debug(err, 'error')
    }
  }, {"X-Merchant-ID": shopList.value[shopIndex.value].shop_id})
}

/**
 * 计算日营业额
 * @return {Promise<void>}
 */
const getDayBusiness = () => {
  const params = {
    page: pagesData.value.page,
    limit: pagesData.value.limit,
    begin_date: betweenTime.value[0] + ' 12:00:00',
    end_date: betweenTime.value[1] + ' 12:00:00'
  }
  if (typeAreaIndex.value == 0) {
    params.area_id = areaChooseArray.value.join()
  }
  if (typeAreaIndex.value == 1) {
    params.type_id = typeChooseArray.value.join()
  }
  commonJs.queryCache('/app/admin/getMoneyEveryDay', params, {
    before() {
      loading.value.show('加载中...')
    },
    success(res) {
      try {
        const {
          code,
          data,
          msg,
          server_ip
        } = res
        if (data.hasOwnProperty('list') && data.hasOwnProperty('count')) {
          dayBusinessList.value = [...dayBusinessList.value, ...data.list]
          pagesData.value.total = data.count
        }
      } catch (error) {
        commonJs.showMessage(error)
      }
    },
    fail(err) {
      commonJs.logger.debug(err, 'error')
    },
    complete() {
      loading.value.hide()
    }
  }, {"X-Merchant-ID": shopList.value[shopIndex.value].shop_id})
}

/**
 * 计算日期差值
 * @param date1
 * @param date2
 * @return {number}
 */
const getDaysDifference = (date1, date2) => {
  const d1 = new Date(date1)
  const d2 = new Date(date2)
  const timeDiff = d2.getTime() - d1.getTime()
  const dayDiff = timeDiff / (1000 * 3600 * 24)
  return Math.abs(dayDiff)
}

/**
 * 获取门店区域列表
 */
const getAreaList = () => {
  const params = {}
  commonJs.queryCache('/finance/getAreaList', params, {
    before() {
    },
    success(res) {
      try {
        const {
          code,
          data,
          msg,
          server_ip
        } = res
        areaTypeList.value.area = data.map(item => {
          item.area_id = String(item.area_id)
          item.checked = false
          return item
        })
      } catch (error) {
        commonJs.showMessage(error)
      }
    },
    fail(err) {
      commonJs.logger.debug(err, 'error')
    }
  }, {"X-Merchant-ID": shopList.value[shopIndex.value].shop_id})
}

/**
 * 获取门店类型列表
 */
const getTypeList = () => {
  const params = {}
  commonJs.queryCache('/admin/room/roomType', params, {
    before() {
    },
    success(res) {
      try {
        const {
          code,
          data,
          msg,
          server_ip
        } = res
        areaTypeList.value.type = data.map(item => {
          item.type_id = String(item.type_id)
          item.checked = false
          return item
        })
      } catch (error) {
        commonJs.showMessage(error)
      }
    },
    fail(err) {
      commonJs.logger.debug(err, 'error')
    }
  }, {"X-Merchant-ID": shopList.value[shopIndex.value].shop_id})
}
</script>
<style scoped lang="scss">
.scroll {
  height: calc(100vh - 148rpx - 88rpx - 68rpx - var(--status-bar-height));
  box-sizing: border-box;
  display: flex;
  position: absolute;
  top: calc(var(--status-bar-height) + 148rpx + 88rpx + 68rpx);
}

.show-type-list {
  display: flex;
  flex-direction: row;
  height: 54rpx;
  padding: 0 30rpx;
  align-items: center;

  .text-space {
    flex-wrap: nowrap;
    flex: 1;
    white-space: nowrap;
    align-items: center;

    .text-name {
      font-size: 26rpx;
      color: var(--white-text);
    }
  }
}

.choose-type-area {
  margin-left: 20rpx;
  font-size: 26rpx;
  color: var(--grey-text);
  display: flex;
  align-items: center;
}

:deep(checkbox uni-checkbox::before) {
  color: var(--area-color) !important;
  z-index: 102;
}

:deep(.uni-checkbox-wrapper .uni-checkbox-input) {
  background-color: var(--area-color) !important;
  z-index: 102;
  border: 1px solid #cdcdcd;
}
</style>